<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>批量生成Mask</title>
    <style>
        .image-preview {
            margin-top: 20px;
            width: 100%;
        }

        .image-container {
            display: inline-block;
            margin: 10px;
            border: 1px solid #ccc;
        }

        .image-container img {
            width: 50px;
            height: auto;
            display: block;
            
        }
    </style>

    <script src="./js/jquery-1.11.1.min.js"></script>
    <script src="./js/jszip.min.js"></script>
    <script src="./js/FileSaver.js"></script>
</head>

<body>
    <h1>批量生成Mask</h1>
    <input type="file" id="fileInput" multiple accept="image/*">
    <br><br>
    
    <button onclick="toMaskData()" id="generatedButton">生成Mask</button>

    总数：<span id="total"></span>，成功数量：<span id="successCount"></span>，失败数量：<span id="failedCount"></span>

    <br><br>
    <button onclick="saveButton()" id="downloadButton">保存Mask</button>

    <div class="image-preview" id="imagePreview"></div>

    <script>
        var saveImages = [];
        async function toMaskData() {
            const files = document.getElementById('fileInput').files;

            if(files.length <= 0) {
                alert('请选择图片')
                return;
            }

            const previewContainer = document.getElementById('imagePreview');
            previewContainer.innerHTML = ''; // 清空预览区域

            saveImages = [];
            let errCount = 0;

            document.getElementById('total').innerText = files.length;
            document.getElementById('successCount').innerText = 0;
            document.getElementById('failedCount').innerText = 0;
            document.getElementById('generatedButton').textContent = '生成中...';
            document.getElementById('generatedButton').disabled = true;

            Array.from(files).forEach(file => {
                console.log(file)
                const reader = new FileReader();
                reader.onload = function (e) {
                    const img = new Image();
                    img.onload = function () {

                        console.log('toMaskData')
                        let originalCanvas = document.createElement('canvas'); // 用于绘制原始PNG图像
                        let originalContext = originalCanvas.getContext('2d');

                        let displayCanvas = document.createElement('canvas'); // 用于显示处理后的图像
                        let displayContext = displayCanvas.getContext('2d');

                        originalCanvas.width = img.width;
                        originalCanvas.height = img.height;
                        originalContext.drawImage(img, 0, 0, img.width, img.height);

                        // 在绘制前清空显示Canvas并填充为黑色
                        displayCanvas.width = originalCanvas.width;
                        displayCanvas.height = originalCanvas.height;
                        displayContext.fillStyle = 'black';
                        displayContext.fillRect(0, 0, displayCanvas.width, displayCanvas.height);

                        // 获取原始Canvas上的图像像素数据，并遍历每个像素进行处理
                        let imageData = originalContext.getImageData(0, 0, originalCanvas.width, originalCanvas.height);

                        let data = imageData.data;
                        for (let i = 0; i < data.length; i += 4) {
                            let alpha = data[i + 3];
                            if (alpha !== 0) {
                                // 如果像素不是完全透明的
                                data[i] = 255; // 设置红色通道为255（白色）
                                data[i + 1] = 255; // 设置绿色通道为255（白色）
                                data[i + 2] = 255; // 设置蓝色通道为255（白色）
                            }
                        }

                        originalContext.putImageData(imageData, 0, 0);

                        // 将处理后的图像绘制到显示Canvas上
                        displayContext.drawImage(originalCanvas, 0, 0);
                        let maskBase64 = displayCanvas.toDataURL('image/png');

                        const resultImage = new Image();
                        resultImage.src = displayCanvas.toDataURL('image/png');
                        const container = document.createElement('div');
                        container.classList.add('image-container');
                        container.appendChild(resultImage);
                        previewContainer.appendChild(container);

                        saveImages.push({
                            name: file.name,
                            dataURL: resultImage.src
                        })

                        document.getElementById('successCount').innerText = saveImages.length;

                        if(saveImages.length + errCount === files.length) {
                            document.getElementById('generatedButton').textContent = '生成Mask';
                            document.getElementById('generatedButton').disabled = false;
                        }
                    }
                    img.onerror = function (e) {
                        errCount++;
                        document.getElementById('successCount').innerText = errCount;

                        if(saveImages.length + errCount === files.length) {
                            document.getElementById('generatedButton').textContent = '生成Mask';
                            document.getElementById('generatedButton').disabled = false;
                        }
                    }
                    img.src = e.target.result;
                }

                reader.onerror = function (e) {
                    errCount++;
                    document.getElementById('successCount').innerText = errCount;

                    if(saveImages.length + errCount === files.length) {
                        document.getElementById('generatedButton').textContent = '生成Mask';
                        document.getElementById('generatedButton').disabled = false;
                    }
                }
                reader.readAsDataURL(file);
            });
        };

        function saveButton() {
            if (saveImages.length === 0) {
                alert('暂无图片');
                return;
            }
            downloadAndCompressFiles(saveImages)
        }

        function base64ToBlob(dataurl) {
            let arr = dataurl.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        }

        function downloadAndCompressFiles(fileList, outputName, callback, progressCb) {
            console.log('fileList', fileList);
            // 创建一个新的JSZip实例
            let zip = new JSZip();
            let fileNames = [];

            // 用于追踪已下载的文件数量和下载失败的文件数量
            let downloadedFiles = 0;
            let failedFiles = 0;

            // 遍历文件列表，下载并添加到压缩包中
            fileList.forEach(function (item, index) {
                // let originalFileName = getFileName(url, true);
                let blob = base64ToBlob(item.dataURL);

                let baseName = item.name.replace(/\.[^/.]+$/, ''); // Remove extension from filename

                let fileName = baseName + '.png';

                // 重名文件，添加序号
                if (fileNames.includes(fileName)) {
                    let count = 1;

                    while (fileNames.includes(fileName)) {
                        fileName = baseName + '(' + count + ').' + 'png';
                        count++;
                    }
                }
                // 将文件数据添加到压缩包中
                zip.file(fileName, blob);
                fileNames.push(fileName);

                // 更新已下载的文件数量
                downloadedFiles++;

                if(progressCb && typeof progressCb === 'function') {
                    progressCb({
                        total: fileList.length,
                        failedCount: failedFiles,
                        successCount: downloadedFiles,
                    })
                }
                    
                // 检查是否所有文件都已下载完成
                if (downloadedFiles === fileList.length) {
                    // 检查是否有文件下载失败
                    if (failedFiles === 0) {
                        // 生成压缩包
                        zip.generateAsync({ type: 'blob' }).then(function (content) {
                            // 确定保存的文件名
                            let saveFileName;
                            if (outputName) {
                                saveFileName = outputName.endsWith('.zip') ? outputName : outputName + '.zip';
                            } else {
                                saveFileName = 'download.zip';
                            }

                            // 使用file-saver库保存压缩包
                            saveAs(content, saveFileName);

                            // 调用回调函数，传递下载成功的文件数量
                            if (callback) {
                                callback(downloadedFiles);
                            }
                        });
                    } else {
                        // 调用回调函数，传递下载成功的文件数量和下载失败的文件数量
                        if (callback) {
                            callback(downloadedFiles, failedFiles);
                        }
                    }
                }
            });
        }
    </script>
</body>

</html>